using System;
using System.ServiceModel;
using System.Windows.Input;

// ReSharper disable UnusedMember.Global

namespace MusicStore.Wpf.Toolkit.Commands
{
  public abstract class ServiceCommandBase<TInterface, TClient> : CommandCore, ICommand
    where TInterface : class
    where TClient : ClientBase<TInterface>
  {
    private TClient mClient;

    private bool IsClientCreated
    {
      get { return mClient != null; }
    }

    #region ICommand Members

    public override Boolean CanExecute(Object parameter)
    {
      return CanExecute(GetClient()) && !IsExecuting;
    }

    public override void Execute(Object parameter)
    {
      try
      {
        if (!CanExecute(GetClient())) return;

        if (OnExecutingCore())
        {
          Execute(GetClient());
        }
      }
      catch (Exception exception)
      {
        OnExecutedCore(CommandExecutionResult.FromException(exception));
      }
    }

    #endregion

    private TClient GetClient()
    {
      if (IsClientCreated) return mClient;
      mClient = CreateServiceClient();
      return mClient;
    }

    private static TClient CreateServiceClient()
    {
      var wClient = (TClient) Activator.CreateInstance(typeof (TClient),
                                                       "BasicHttpBinding_ISales");
      return wClient;
    }

    protected abstract bool CanExecute(TClient client);

    protected abstract void Execute(TClient client);
  }
}

// ReSharper restore UnusedMember.Global